package api

import (
	"awesomeProject/userop-web/global"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"net/http"
	"strings"
)

func removeTopStruct(fields map[string]string) map[string]string {

	rsp := map[string]string{}

	for filed, err := range fields {
		rsp[filed[strings.Index(filed, ".")+1:]] = err
	}
	return rsp
}

// HandleValidateError 进行表单验证的内部逻辑
func HandleValidateError(err error, c *gin.Context) {

	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		c.JSON(http.StatusOK, gin.H{"msg": err.Error()})
	}
	c.JSON(http.StatusBadRequest, gin.H{"error": removeTopStruct(errs.Translate(global.Trans))})
}

// HandleGrpcErrorToHttp 将Grpc的错误转化为HTTP的错误
func HandleGrpcErrorToHttp(err error, c *gin.Context) {
	if err == nil {
		return
	}
	// 错误不为空才进行转换
	e, ok := status.FromError(err)
	if ok {
		switch e.Code() {
		case codes.NotFound:
			c.JSON(http.StatusNotFound, gin.H{"msg": e.Message()})
		case codes.Internal:
			c.JSON(http.StatusInternalServerError, gin.H{"msg": "内部错误"})
		case codes.InvalidArgument:
			c.JSON(http.StatusBadRequest, gin.H{"msg": "参数错误"})
		default:
			c.JSON(http.StatusInternalServerError, gin.H{"msg": "其他错误"})
		}
	}
}
